/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.ListIterator;

import com.hiddenequity.campaign_targeting_service.CampaignTargetingResponseParser;
import com.hiddenequity.campaign_targeting_service.CampaignTargetingService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.Language;
import com.hiddenequity.utils.LocationDataProvider;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;

public class Act_CampaignLangTarget extends Act_Super {
	
	private String campaignId;
	
	private String campaignName;
	
	private ListView lView;
		
	private static ArrayList<Language> languageList = new ArrayList<Language>();
	
	private SparseBooleanArray checked = new SparseBooleanArray();

	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_campaign_lang_target)).inflate();
        
        //Get intent data
        Intent intent = getIntent();
        campaignId = intent.getStringExtra("campaignId");
        campaignName = intent.getStringExtra("campaignName");
        
        //Set up custom title
        title.setText(R.string.title_language_set);
        sub_title.setText(campaignName);
        filter.setVisibility(View.GONE);
        
        runOperationasync(OPERATION_PREPARE_DATA, getString(R.string.progress_preparing), false);
        
    }//onCreate
    
    
    
    /*
     * Get language list
     */
    private void getLanguageList(){
    	languageList = LocationDataProvider.getLanguageList(getApplication());
    }//getLanguageList
   
    
    
    /*
     * Setup language list
     */
    private void setUpLanguageList(){
        lView = (ListView) findViewById(R.id.list_campaignLanguage);
        LanguageAdapter m_adapter = new LanguageAdapter(this, R.layout.list_row_language, languageList);
        lView.setAdapter(m_adapter);
    
        lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
            		int position, long id) {
            	
            	boolean check = !((CheckedTextView) view).isChecked();
            	if(!check){
            		checked.delete(position);
            	} else {
            		checked.append(position, check);
            	}
            }
        });

        ListIterator<Language> code = languageList.listIterator();
		
		while(code.hasNext()){
			String langCode = code.next().getCode();
			if(usedLangaugeList.contains(langCode)){
				lView.setItemChecked(code.nextIndex()-1, true);
				checked.append(code.nextIndex()-1, true);
			}
		}   	
    }
 
    
    
	/*
	 * Asinc data request
	 */
	private void runOperationasync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_CampaignLangTarget.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_CampaignLangTarget.this
									.getCampaignLanguageTargeting();
							break;
						case OPERATION_PREPARE_DATA:
							Act_CampaignLangTarget.this.getLanguageList();
							break;
						case OPERATION_SET_DATA:
							Act_CampaignLangTarget.this
									.setCampaignLanguageTargeting();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_CampaignLangTarget.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								Act_CampaignLangTarget.this.setUpLanguageList();
								break;
							case OPERATION_PREPARE_DATA:
								runOperationasync(OPERATION_GET_DATA,
										getString(R.string.progress_loading),
										true);
								break;
							case OPERATION_SET_DATA:
								Act_CampaignLangTarget.this.finish();
								break;
							}
							
						} else {
							Intent intent = new Intent(
									Act_CampaignLangTarget.this
											.getApplicationContext(),
									Act_Login.class);
							
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationasync
	
	
	
    /*
     * Custom List adapter for Language type
     */
    public class LanguageAdapter  extends ArrayAdapter<Language> {

        private ArrayList<Language> items;

        public LanguageAdapter(Context context, int textViewResourceId, ArrayList<Language> items) {
        	super(context, textViewResourceId, items);
        	this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list_row_language, null);
            }
            Language lang = items.get(position);
            if (lang != null) {
            	CheckedTextView tt = (CheckedTextView) v.findViewById(R.id.languageName);
            	if (tt != null) {
            		tt.setText(lang.getName());            	
            	}

            }
            return v;
        }

    }//Custom adapter
    
    
    
    /*
     * Get campaign language list
     */
    private ArrayList<String> usedLangaugeList = new ArrayList<String>();
    
    private void getCampaignLanguageTargeting(){
    	CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
    			Communication.postSOAP(
					CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
					CampaignTargetingService.getCampaignTargetById(campaignId)
					)
    			);
    	
    	responseErrorString = targetingParser.checkForErrors();
    	usedLangaugeList.addAll(targetingParser.getCampaignLangTarget());
    }//getCampaigntargetData
    
    
    
    /*
     * Set campaign
     */
    private void setCampaignLanguageTargeting(){
        
        CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
        		Communication.postSOAP(
    				CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    				CampaignTargetingService.setLangTarget(campaignId, usedLangaugeList)
    				)
        		);
        	
        responseErrorString = targetingParser.checkForErrors();
    }//setCampaignLanguageTargeting
    
    
    
    /*
     * Save button click handler
     */
    public void onClick_saveData(View v){
    	usedLangaugeList.clear();
    	
    	for (int i = 0; i < checked.size(); i++){
    		usedLangaugeList.add(languageList.get(checked.keyAt(i)).getCode());
    	}
    	
    	runOperationasync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);    	
    }//onClick_saveData

}
